<?php
namespace app\admin\controller;

use app\common\service\Post as PostService;
use think\Controller;
use think\Request;

class Post extends Controller{

    public function index(){

        $postService = new PostService();

        $posts = $postService -> paginate();

        return view('',['posts'=>$posts]);
    }

    public function add(){

        $postService = new PostService();
        $postClass = $postService->getAllPostClass();

        return view('',['postClass'=>$postClass]);
    }

    public function create( Request $request ){
        if(!$request->isPost()){
            $this->error("非法途径访问");
        }

        $data = $request->only(['title','desc','cover','pc_id','content']);

        $postService = new PostService();
        $result = $postService ->insert($data);

        if($result['state']) {
            $this->success("操作成功");
        }else{
            $this->error($result['message']);
        }

    }


    public function edit(Request $request){

        $ids = $request -> only("id");
        if(count($ids)>1) $this->error("访问来源错误");

        $postService = new PostService();
        $post = $postService -> all($ids)[0];

        $postClass = $postService->getAllPostClass();

        return view('',['post'=>$post,'postClass'=>$postClass]);
    }


    public function update(Request $request){

        if(!$request->isPost()){
            $this->error("非法途径访问");
        }
        $data = $request->only(['id','title','desc','cover','pc_id','content']);

        $postService = new PostService();
        $result = $postService ->update($data);

        if(1 == $result['state']) {
            $this->success("操作成功");
        }else{
            $this->error("操作失败");
        }
    }


    public function delete(Request $request){
        if(!$request->isDelete()){
            $this->error("非法访问途径");
        }

        $param = $request->only(['id']);
        if(count($param) !== 1){
            $this->error("禁止批量操作");
        }

        $postService = new PostService();
        $count = $postService -> delete($param['id']);

        if($count){
            $this->success("操作成功");
        }else{
            $this->error("操作失败");
        }

    }

}